import React, { useState } from 'react';
import { Upload, App } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import type { UploadFile } from 'antd/es/upload/interface';
import COS from 'cos-js-sdk-v5';
import baseApi from '../../services/baseApi';

interface ImageUploadProps {
  value?: string;
  onChange?: (url: string) => void;
  maxCount?: number;
  listType?: 'text' | 'picture' | 'picture-card';
  disabled?: boolean;
  accept?: string;
  folder?: string;
}

const ImageUpload: React.FC<ImageUploadProps> = ({
  value,
  onChange,
  maxCount = 1,
  listType = 'picture-card',
  disabled = false,
  accept = 'image/*',
  folder = 'okeydo'
}) => {
  const { message } = App.useApp();
  const [uploading, setUploading] = useState(false);
  const [fileList, setFileList] = useState<UploadFile[]>(() => {
    if (value) {
      return [{
        uid: '-1',
        name: 'image.jpg',
        status: 'done',
        url: value
      }];
    }
    return [];
  });

  // 初始化COS实例
  const initCOS = async () => {
    try {
      const response = await baseApi.get('/admin/cos/token');
      const result = response.data;
      
      if (result.code === 0) {
        const { credentials, bucket, region } = result.data;
        
        const cos = new COS({
          SecretId: credentials.tmpSecretId,
          SecretKey: credentials.tmpSecretKey,
          SecurityToken: credentials.sessionToken,
        });
        
        return { cos, bucket, region };
      } else {
        throw new Error(result.message || '获取COS凭证失败');
      }
    } catch (error) {
      console.error('初始化COS失败:', error);
      throw error;
    }
  };

  // 文件上传到COS
  const handleImageUpload = async (file: File) => {
    setUploading(true);
    try {
      const { cos, bucket, region } = await initCOS();
      
      // 生成文件名
      const timestamp = Date.now();
      const randomStr = Math.random().toString(36).substring(2);
      const fileExtension = file.name.split('.').pop();
      const fileName = `${folder}/${timestamp}_${randomStr}.${fileExtension}`;

      // 上传到COS
      await new Promise<void>((resolve, reject) => {
        cos.putObject({
          Bucket: bucket,
          Region: region,
          Key: fileName,
          Body: file,
        }, (err: unknown) => {
          if (err) {
            reject(err);
          } else {
            resolve();
          }
        });
      });

      // 构建CDN地址
      const cdnUrl = `https://${bucket}.cos.${region}.myqcloud.com/${fileName}`;
      console.log(cdnUrl);

      const newFileList: UploadFile[] = [{
        uid: '-1',
        name: file.name,
        status: 'done',
        url: cdnUrl
      }];
      setFileList(newFileList);
      onChange?.(cdnUrl);
      message.success('图片上传成功');
      return false; // 阻止默认上传行为
    } catch (error) {
      console.error('上传失败:', error);
      message.error('图片上传失败');
      return false;
    } finally {
      setUploading(false);
    }
  };

  return (
    <Upload
      listType={listType}
      fileList={fileList}
      onChange={({ fileList: newFileList }) => setFileList(newFileList)}
      beforeUpload={handleImageUpload}
      maxCount={maxCount}
      accept={accept}
      disabled={disabled}
    >
      {fileList.length < maxCount && (
        <div>
          <UploadOutlined />
          <div style={{ marginTop: 8 }}>
            {uploading ? '上传中...' : '上传图片'}
          </div>
        </div>
      )}
    </Upload>
  );
};

export default ImageUpload; 